package org.phalanx.servlet.webmessages;

import java.io.IOException;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.phalanx.server.PhalanxServer;
import org.phalanx.server.ServerCache.CacheManager;
import org.phalanx.server.user.PhalanxUser;
import org.phalanx.servlet.websession.ServletAuthenticatorManager;
import org.phalanx.servlet.websession.UserWebSession;

public class FeedListener implements WebMessageable {
	public static final String LISTEN_FEED_CONTEXT = "listenfeed";
	private PhalanxServer pServer;
	private Cookie authCookie;


	public FeedListener (PhalanxServer pServer){
		this.pServer = pServer;
	}

	private void listenFeed(HttpServletResponse resp) throws IOException{
		resp.setContentType("text/plain");
		ServletAuthenticatorManager s = new ServletAuthenticatorManager(pServer);
		
		if (authCookie != null && s.authenticate(authCookie) != null){
			// Add user to web feed

			CacheManager cacheMgr = pServer.getCacheManager();
			PhalanxUser u = (PhalanxUser)cacheMgr.getElement("TokenSessionCache", authCookie.getValue());

			// Check if there are other feeds
			UserWebSession session = (UserWebSession)cacheMgr.getElement("UserWebFeedCache", u.getId());

			if (session == null){
				session = new UserWebSession(u.getId());
				cacheMgr.setElement("UserWebFeedCache", u.getId(), session);
			}
			boolean timeOut = false;
			int i = 0;

			Integer feedId = null;
			session.getNewFeedId();
			feedId = session.getFeedId();
			
			while (!timeOut){
				try {
					Thread.sleep(1000);
					if (!session.hasFeedId(feedId)){
						break;
					}
					if (i >= 30){
						timeOut = true;
					}else {
						if (session.hasQueueItems()){
							synchronized(session){
								String queueText = session.getQueueThenClear();
								System.out.println(queueText);
								resp.getWriter().write(queueText);
								resp.getWriter().flush();
								timeOut = true;
							}
						} // if
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					break;
				}
				i++;
			} // while
		}
	}


	@Override
	public void onContextLoadable(String context, Cookie authCookie,
			HttpServletRequest req, HttpServletResponse resp) {
		try {
			if (context.equals(LISTEN_FEED_CONTEXT)){
				this.authCookie = authCookie;
				this.listenFeed(resp);
			}
		} catch (IOException ie){
			ie.printStackTrace();
		}
	}

}
